<template>
	<view class="page">
		
			<view style="padding: 30rpx 30rpx 240rpx;">
				<view class="message" :class="[item.userType]" v-for="(item, index) in list" :key="index">
					<!-- 对方消息 -->
					<image :src="`http://localhost:8080${item.avatar}`" 
					       v-if="item.userType === 'friend'" 
					       class="avatar" 
					       mode="widthFix" 
					       @click="goToFriendProfile()">
					</image>
					<!-- 消息内容 -->
					<view class="content" v-if="item.messageType === 'image'">
						<image :src="item.content" mode="widthFix"></image>
					</view>
					<view class="content" v-else>
						{{ item.message }}
					</view>
					<!-- 自己的消息 -->
					<image :src="`http://localhost:8080${item.avatar}`" v-if="item.userType === 'self'" class="avatar"
						mode="widthFix"></image>
				</view>
			</view>
		</scroll-view>
		<view class="tool">
			<input type="text" v-model="content" class="input" @confirm="send" />
			<image src="/static/chat/photo.png" mode="widthFix" class="thumb" @click="chooseImage"></image>
			<button class="send-btn" @click="send">发送</button>
		</view>
	</view>
</template>

<script>
	import user from '../../store/modules/user';
import {
		queryHistory,
		saveMessage
	} from '@/api/msg/msg.js'

import {getUserInfoById} from '@/api/my/user.js'
	export default {
		data() {
			return {
				content: '',
				list: [],
				top: 0, // 用于控制滚动的位置
				receiverId: '',
				senderId: this.$store.state.user.userId,
				scrollHeight: 0, // 页面滚动区域的高度
				userInfo:''
			};
		},
		created() {
			this.getHistory();
		},

		onShow() {
			this.scrollToBottom();
		},
		onLoad(options) {
			uni.setNavigationBarTitle({
				title: options.name
			});
			this.receiverId = options.userId;
			this._friendAvatar = options.avatar;
			this._selfAvatar = this.$store.state.user.avatar;

			this.list = [{
					content: '对方历史回复消息',
					userType: 'friend',
					avatar: this._friendAvatar
				},
				{
					content: '历史消息',
					userType: 'self',
					avatar: this._selfAvatar
				}
			];
		},
		mounted() {
			this.scrollToBottom(); // 初次加载时滚动到底部
			this.setScrollHeight(); // 设置滚动区域的高度

			// 监听消息接收
			this.$socket.getMessage((res) => {
				const data = JSON.parse(res.data);
				const replyMessage = {
					message: data.content,
					userType: "friend",
					avatar: this._friendAvatar,
				};
				this.list.push(replyMessage);
				this.scrollToBottom(); // 新消息后滚动到底部
			});
		},
		watch: {
		  list() {
		    this.setScrollHeight();  // 监听 list 的变化并重新计算高度
		    this.scrollToBottom();   // 更新消息列表时，确保滚动到底部
		  }
		},

		methods: {
			send() {
				if (!this.content.trim()) {
					console.warn("发送内容为空");
					return;
				}

				const selfMessage = {
					message: this.content,
					userType: 'self',
					avatar: this._selfAvatar,
				};
				this.list.push(selfMessage);

				if (this.$socket) {
					const message = {
						content: this.content,
						type: "chat",
						senderId: this.senderId,
						receiverId: this.receiverId,
						timestamp: new Date().toISOString(),
					};
					this.$socket.send(JSON.stringify(message));

					const messageData = {
						message: this.content,
						type: "chat",
						senderId: this.senderId,
						receiverId: this.receiverId,
						timestamp: new Date().toISOString(),
					};
					saveMessage(messageData)
						.then(response => {
							console.log('消息保存成功:', response);
						})
						.catch(error => {
							console.error('消息保存失败:', error);
						});
				} else {
					console.error("WebSocket 工具类未初始化或方法不存在");
				}

				this.content = '';
				this.scrollToBottom(); // 发送后滚动到底部
			},


			chooseImage() {
				uni.chooseImage({
					success: (res) => {
						this.list.push({
							content: res.tempFilePaths[0],
							userType: 'self',
							messageType: 'image',
							avatar: this._selfAvatar
						});
						this.scrollToBottom(); // 新图片发送后滚动到底部
						if (this.$socket) {
							const message = {
								content: this.content,
								type: "chat",
								senderId: this.senderId,
								receiverId: this.receiverId,
								timestamp: new Date().toISOString(),
							};
							this.$socket.send(JSON.stringify(message));
						} else {
							console.error("WebSocket 工具类未初始化或方法不存在");
						}
					}
				});
			},

			getHistory() {
				this.scrollToBottom();
				queryHistory(this.senderId, this.receiverId).then(res => {
					if (res.data && Array.isArray(res.data)) {
						this.list = res.data.map(item => {
							item.userType = item.senderId === Number(this.senderId) ? 'self' : 'friend';
							item.avatar = item.senderId === this.senderId ? this._selfAvatar : this
								._friendAvatar;
							return item;
						});
						
					} else {
						console.error('未返回有效的聊天记录数据');
					}
				}).catch(error => {
					console.error('获取聊天记录失败:', error);
				});
			},

			setScrollHeight() {
				this.scrollHeight = uni.getSystemInfoSync().windowHeight ; // 减去工具栏的高度
			},

			scrollToBottom() {
				this.$nextTick(() => {
					setTimeout(() => {
						const query = uni.createSelectorQuery().in(this);
						query.select('.scroll-view').boundingClientRect(rect => {
							if (rect) {
								this.top = rect.height;
								this.$refs.scrollView.scrollTop = rect.height;
							}
						}).exec();
					}, 200); // 增加延迟时间，确保渲染完成
				});
			},
			
			 goToFriendProfile() {
				 const userId = this.receiverId
			        if (this.receiverId !== this.senderId) {  
						getUserInfoById(userId).then((res) => {
							console.log(res);
							this.userInfo =res.data
							uni.navigateTo({
							    url: `/pages/my/detailPages?item=${encodeURIComponent(JSON.stringify(this.userInfo))}`
							});
						})
						.catch((error) => {
							
						})
					
			         
			        }
			    },
		}
	};
</script>

<style lang="scss" scoped>
	.scroll-view {
		background: #eee;
		box-sizing: border-box;
	}

	.message {
		display: flex;
		align-items: flex-start;
		margin-bottom: 30rpx;

		.avatar {
			width: 80rpx;
			height: 80rpx;
			border-radius: 10rpx;
			margin-right: 30rpx;
		}

		.content {
			min-height: 80rpx;
			max-width: 60vw;
			box-sizing: border-box;
			font-size: 28rpx;
			line-height: 1.3;
			padding: 20rpx;
			border-radius: 10rpx;
			background: #fff;

			image {
				width: 200rpx;
			}
		}

		&.self {
			justify-content: flex-end;

			.avatar {
				margin: 0 0 0 30rpx;
			}

			.content {
				position: relative;

				&::after {
					position: absolute;
					content: '';
					width: 0;
					height: 0;
					border: 16rpx solid transparent;
					border-left: 16rpx solid #fff;
					right: -28rpx;
					top: 24rpx;
				}
			}
		}

		&.friend {
			.content {
				position: relative;

				&::after {
					position: absolute;
					content: '';
					width: 0;
					height: 0;
					border: 16rpx solid transparent;
					border-right: 16rpx solid #fff;
					left: -28rpx;
					top: 24rpx;
				}
			}
		}
	}

	.tool {
		position: fixed;
		width: 100%;
		min-height: 120rpx;
		left: 0;
		bottom: 0;
		background: #fff;
		display: flex;
		align-items: flex-start;
		box-sizing: border-box;
		padding: 20rpx 24rpx 20rpx 40rpx;
		padding-bottom: calc(20rpx + constant(safe-area-inset-bottom)/2) !important;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom)/2) !important;

		.input {
			background: #eee;
			border-radius: 10rpx;
			height: 70rpx;
			margin-right: 30rpx;
			flex: 1;
			padding: 0 20rpx;
			box-sizing: border-box;
			font-size: 28rpx;
		}

		.thumb {
			width: 64rpx;
		}

		.send-btn {
			background-color: #007aff;
			color: #fff;
			border: none;
			border-radius: 10rpx;
			padding: 0 30rpx;
			height: 70rpx;
			line-height: 70rpx;
			font-size: 28rpx;
			cursor: pointer;
			margin-left: 20px;
		}
	}
</style>
